package com.cema.manage.project.manage.proOrder.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cema.manage.common.exception.BizException;
import com.cema.manage.project.manage.proGoods.domain.ProGoods;
import com.cema.manage.project.manage.proGoods.service.IProGoodsService;
import com.cema.manage.project.manage.proOrder.domain.ProOrder;
import com.cema.manage.project.manage.proOrder.mapper.ProOrderMapper;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.manage.users.service.IUsersService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 订单管理 服务层实现
 *
 * @author reasahi
 * @date 2024-11-05
 */
@Service
public class ProOrderServiceImpl extends ServiceImpl<ProOrderMapper, ProOrder> implements IProOrderService {
    @Resource
    private IProGoodsService iProGoodsService;

    @Resource
    private IUsersService iUsersService;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void createOrder(int usId, int pgId) {
        lock.lock();
        try {
            ProGoods proGoods = iProGoodsService.selectById(pgId);
            if (ObjectUtil.isNull(proGoods)) {
                throw new BizException("无效商品");
            }
            Users users = iUsersService.selectById(usId);
            if (ObjectUtil.isNull(users)) {
                throw new BizException("无效用户");
            }
            int money = users.getMoneyGoldCoin() - proGoods.getPgMoney();
            if (money < 0) {
                throw new BizException("金币不足");
            }
            ProOrder proOrder = new ProOrder();
            proOrder.setUsId(usId);
            proOrder.setPgId(pgId);
            proOrder.setPgMoney(proGoods.getPgMoney());
            proOrder.setPgTitle(proGoods.getPgTitle());
            proOrder.setPoId(UUID.randomUUID().toString().replace("-", StrUtil.EMPTY));
            insert(proOrder);

            Users usersUpdate = new Users();
            usersUpdate.setId(usId);
            usersUpdate.setMoneyGoldCoin(money);
            iUsersService.updateById(usersUpdate);
        } finally {
            lock.unlock();
        }
    }
}
